package com.igor.tarefas.controllers;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import com.igor.tarefas.database.TarefaDao;
import com.igor.tarefas.model.Tarefa;

@Controller
public class TarefasController {
	@RequestMapping("novaTarefa")
	public String form() {
		return "tarefa/formulario";
	}

	@RequestMapping("adicionaTarefa")
	public String adiciona(@Valid Tarefa tarefa, BindingResult result) {
		if (result.hasErrors()) {
			return "tarefa/formulario";
		}
		TarefaDao dao = new TarefaDao();
		dao.adiciona(tarefa);
		return "tarefa/adicionada";
	}

	@RequestMapping("listaTarefas")
	public String lista(Model model) {
		/*
		 * TarefaDao dao = new TarefaDao(); List<Tarefa> tarefas =
		 * dao.getLista(); ModelAndView mv = new ModelAndView("tarefa/lista");
		 * mv.addObject("tarefas", tarefas); return mv;
		 */
		TarefaDao dao = new TarefaDao();
		model.addAttribute("tarefas", dao.getLista());
		return "tarefa/lista";
	}

	@RequestMapping("removeTarefa")
	public String remove(Tarefa tarefa) {
		TarefaDao dao = new TarefaDao();
		dao.remove(tarefa);
		return "redirect:listaTarefas";
	}
	@RequestMapping("finalizaTarefa")
	public void finaliza(Long id, HttpServletResponse response) {
		TarefaDao dao = new TarefaDao();
		dao.finaliza(id);
		response.setStatus(200);
	}
}
